import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { AllotManageContext, IAllotActionEnum } from '../mconfig';
import { materialTableService } from '../services/UpdateTableService';
import { materialTableConfig } from '../mconfig';
import { Col, Row, message } from 'antd';
import { getColorTextLoadMap, getKeyRouter, getLoadMapList, getSelectDataMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { showTotalInfo } from '@/common/constVariable';
import { UpdateTableCommon } from './UpdateTableCommon';
import { ILoadMapTypeAll } from '@/common';
import { AssetAllotManageAPI } from '../common/type';
import _ from 'lodash';

export const OpenMaterialModal: React.FC<AssetAllotManageAPI.IOpenMaterialModal> = ({ onClose, isShowModal, originalStoreID, isTransferType }) => {
  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);
  const styleFixCls = 'contract-styfixcls-';
  // /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
  ]);
  // /** 资产类型 */
  const assetTypeList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);

  /** 获取上下文 */
  const {
    materielList,
    curRes,
    rightTableProps: { materielForm },
    allotDispatch,
  } = useContext(AllotManageContext);
  /** 获取列表 */
  const { data, params, loading, pagination, searchList, loadMdicMapObj, getManageData } = materialTableService(curRes, originalStoreID, isTransferType);

  /** 暂时保存选中的值 */
  const [checkMaterialList, setCheckMaterialList] = useState<Record<string, any>[]>([]);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo) => {
    setCheckMaterialList(selectInfo);
  };

  /** 表格数据 */
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);

  const dataRowMemo = useMemo(() => {
    let dataRow: Record<string, any>[] = [];
    if (data?.rows?.length >= 0) {
      let arr = _.cloneDeep(data?.rows);
      checkMaterialList.map((item) => {
        let i = arr.findIndex((data) => data.materialOrAssetId == item.materialOrAssetId);
        if (i >= 0) {
          arr[i].quantityOrArea = item.quantityOrArea;
        }
      });
      setDataSource(arr);
    }
    return dataRow;
  }, [data]);

  /** 初始化 */
  useEffect(() => {
    setCheckMaterialList(materielList);
  }, [isShowModal]);

  /** 点击确定 */
  const onSave = () => {
    if (checkMaterialList && checkMaterialList?.length > 0) {
      // 存储到仓库
      allotDispatch({
        type: IAllotActionEnum.SELECT_MATERIEL,
        payload: [...checkMaterialList],
      });
      onCloseModalCommon(updateModalRef);
    } else {
      message.error('请至少选择一个物资');
    }
    return;
  };

  /** 修改资产数量 */
  const changeNum = (materialOrAssetId: string | number, value: string | number) => {
    /** 修改表格数量 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === materialOrAssetId;
    });
    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].quantityOrArea = value;
      setDataSource(arr);
    }

    /** 修改选中数量 */
    let checkIdx = checkMaterialList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === materialOrAssetId;
    });
    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkMaterialList);
      arr[checkIdx].quantityOrArea = value;
      if (arr[checkIdx].residueNum) {
        arr[checkIdx].expectNum = arr[checkIdx].residueNum - arr[checkIdx].quantityOrArea;
      } else {
        arr[checkIdx].expectNum = dataSource[checkIdx].residueNum - arr[checkIdx].quantityOrArea;
      }

      setCheckMaterialList(arr);
    }
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={'物资列表'}
        onCancel={onClose}
        width={document.body.clientWidth * 0.65}
        bodyStyle={{
          height: document.body.clientHeight * 0.55,
          padding: 10,
        }}
        onOk={onSave}
      >
        <Row className={`${styleFixCls}materialModal`}>
          <Col>
            <UpdateTableCommon
              styleFixCls={styleFixCls}
              searchProps={{
                searchList,
                onReset,
                onSearch,
              }}
              selectTablePorps={{
                onSelectTable,
                selectRowObjList: checkMaterialList,
                selectType: 'checkbox',
                setCheckRows: setCheckMaterialList,
              }}
              tableProps={{
                columns: materialTableConfig(assetTypeList, changeNum),
                loading,
                dataSource: dataSource, // dataRowMemo,
                pagination,
                onPageChange,
                rowKey: 'materialOrAssetId',
                tableTotalShow: (total: any, range: any) => {
                  return (
                    <div
                      style={{
                        display: 'flex',
                        width: '100%',
                        justifyContent: 'space-between',
                      }}
                    >
                      <div>
                        已选择<strong style={{ color: 'red' }}> {checkMaterialList?.length} </strong>条物资
                      </div>
                      <div>{showTotalInfo(total, range)}</div>
                    </div>
                  );
                },
              }}
              setDataSource={setDataSource}
            />
          </Col>
        </Row>
      </OneModal>
    </>
  );
};
